import Vue from 'vue'
import Vuex from 'vuex'
import localStore from '../utils/localStore'
import { getOauth2AccessToken } from '@/service/api/wechat'

Vue.use(Vuex)

const state = {
  code: '',
  openId: '', // openid o9wVJwmNa0RE_wbMGjSCysoxguXU
  appUser: {}, // 应用用户信息
  userInfo: {}, // 微信用户信息
  myCatalog: [], // 缓存我的分类选择
  firstStatus: '', // 用户第一次登陆状态
  secondStatus: '', // 用户第二次登陆状态
  articleId: '', // 文章ID
  articleParams: {} // 文章参数
}

const mutations = {
  updateCode (state, code) {
    this.state.code = code
  },
  updateFirstStatus (state, code) {
    this.state.code = code
  },
  updateSecondStatus (state, code) {
    this.state.code = code
  },
  updateMyCatalog (state, myCatalog) {
    this.state.myCatalog = myCatalog
  },
  updateArticleId (state, articleId) {
    this.state.articleId = articleId
    localStore.save('articleId', articleId)
  },
  updateArticleParams (state, articleParams) {
    this.state.articleParams = articleParams
  },
  /// //////////////////////////////////////////
  // 01:换取微信openid
  initWeChatOpenId (state, code) {
    console.log('getWeChatOpenId Start: ' + this.state.openId)
    let param = {
      'code': code,
      'openId': this.state.openId
    }
    getOauth2AccessToken(param).then(res => {
      console.log('getWeChatOpenId Start')
      if (res.code === 0 && res.data) {
        if (res.data.appUser) {
          this.state.appUser = res.data.appUser
          localStore.save('appUser', res.data.appUser)
          console.log('fetch store:', localStore.fetch('appUser'))
        }
        if (res.data.userInfo) {
          this.state.userInfo = res.data.userInfo
          localStore.save('userInfo', res.data.userInfo)
          console.log('fetch store:', localStore.fetch('userInfo'))
        }
        if (!res.data.accessToken) {
          console.error('get AccessToken is null by code:' + code)
          return
        }
        this.state.openId = res.data.accessToken.openId
        console.log('getWeChatOpenId Success')
        console.log(this.state)
      } else {
        console.log('getWeChatOpenId Request')
        console.log(res)
      }
    }).catch((error) => {
      console.log('getWeChatOpenId Error')
      console.log(error)
    })
  }
}

const actions = {
  async wechatUserInit ({dispatch}) {
    await dispatch('initOpenId', this.state.code)
  },
  // 01: 获取用户信息
  initOpenId (_this, code) {
    _this.commit('initWeChatOpenId', code)
  }
}

const getters = {
  // 获取用户的信息（public）
  appUserInfo: (state) => {
    return state.appUser || localStore.fetch('appUser')
  },
  wechatUserInfo: (state) => {
    return state.userInfo || localStore.fetch('userInfo')
  },
  myCatalog: (state) => {
    return state.myCatalog
  },
  getArticleId: (state) => {
    return state.articleId || localStore.fetch('articleId')
  },
  getArticleParams: (state) => {
    return state.articleParams
  }
}

export default new Vuex.Store({
  state,
  getters,
  actions,
  mutations
})
